<template>
  <div class="food-content-box activity-info">
    <el-breadcrumb separator="/" class="page-title">
      <el-breadcrumb-item :to="{ path: 'restaurants' }">{{$t('m.Restaurants')}}</el-breadcrumb-item>
      <el-breadcrumb-item>activity</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="search-box container-padding">
      <el-form :inline="true" label-position="top" :model="submitForm" :rules="rules" size="mini" ref="submitForm"  class="form-min-width" v-loading="loading1">
        <div class="container-box label-style">
          <el-row :gutter="20">
            <el-col>
              <el-form-item :label="$t('m.Status')">
                <el-select  style="width: 200px" v-model="submitForm.status" placeholder="" disabled>
                  <el-option v-for="rg in rStatus" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item  style="width: 200px" :label="$t('m.Name')" prop="name">
                <el-input v-model="submitForm.name" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col>
              <el-form-item :label="$t('m.Region')" prop="regionId" >
                <el-select  style="width: 200px" v-model="submitForm.regionId" placeholder="" @change="getTownships($event)" disabled>
                  <el-option v-for="rg in regions" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('m.Township')" prop="townshipId" >
                <el-select  style="width: 200px" v-model="submitForm.townshipId" placeholder="" disabled>
                  <el-option v-for="ts in townships" :key="ts.value" :label="ts.text" :value="ts.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col>
              <el-form-item :label="$t('m.Street')" style="width: 200px" prop="street" >
                <el-input v-model="submitForm.street" disabled></el-input>
              </el-form-item>
              <el-form-item :label="$t('m.Phoneseparatebycomma')" style="width: 200px"  prop="phone">
                <el-input v-model.number="submitForm.phone" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-button type="primary" @click="addNewActivity" size="medium">New activity<i class="el-icon-plus el-icon--right"></i></el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <!--表格-->
      <el-table
        :data="tableData"
        v-loading="tableLoading"
        border
        style="width: 100%;margin-top:20px;">
        <!--Edit-->
        <el-table-column
          prop="Edit"
          label="Edit"
          align="center"
          min-width="80">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editActivity(scope.$index,scope.row)">{{$t('m.Edit')}}</el-button>
          </template>
        </el-table-column>
        <!--Status-->
        <el-table-column
          prop="Status"
          label="Status"
          align="center"
          min-width="120">
          <template slot-scope="scope">
            <div class="list-notes">{{getStatusItem(scope.row.status)}}</div>
          </template>
        </el-table-column>
        <!--Activity Date-->
        <el-table-column
          prop="ActivityDate"
          label="Activity Date"
          align="center"
          min-width="120">
          <template slot-scope="scope">
            <div class="list-notes">{{getActivityDate(scope.row.activityTime)}}</div>
          </template>
        </el-table-column>
        <!--Activity Type-->
        <el-table-column
          prop="ActivityType"
          label="Activity Type"
          align="center"
          min-width="120">
          <template slot-scope="scope">
            <div class="list-notes">{{getActivityTypeItem(scope.row.activityType)}}</div>
          </template>
        </el-table-column>
        <!--Objective-->
        <el-table-column
          prop="Objective"
          label="Objective"
          align="center"
          min-width="120">
          <template slot-scope="scope">
            <div class="" v-html="getObjectiveItem(scope.row.objectives)"></div>
          </template>
        </el-table-column>
        <!--Result-->
        <el-table-column
          prop="Result"
          label="Result"
          align="center"
          min-width="120">
          <template slot-scope="scope">
            <div class="list-notes">{{scope.row.result}}</div>
          </template>
        </el-table-column>
        <!--Created Date-->
        <el-table-column
          prop="CreatedDate"
          label="Created Date"
          align="center"
          min-width="160">
          <template slot-scope="scope">
            <div class="list-notes">{{getDate(scope.row.createDate)}}</div>
          </template>
        </el-table-column>
        <!--Created By-->
        <el-table-column
          prop="CreatedBy"
          label="Created By"
          align="center"
          min-width="120">
          <template slot-scope="scope">
            <div class="list-notes">{{scope.row.createBy}}</div>
          </template>
        </el-table-column>
        <!--Updated Date-->
        <el-table-column
          prop="UpdatedDate"
          label="Updated Date"
          align="center"
          min-width="160">
          <template slot-scope="scope">
            <div class="list-notes">{{getDate(scope.row.updateDate)}}</div>
          </template>
        </el-table-column>
        <!--Updated By-->
        <el-table-column
          prop="UpdatedBy"
          label="Updated By"
          align="center"
          min-width="120">
          <template slot-scope="scope">
            <div class="list-notes">{{scope.row.updateBy}}</div>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="Edit" :visible.sync="dialogFormVisible" @close="editCancelForm()">
        <el-form :inline="true" label-position="top" :model="editForm"  ref="editForm" :rules="editRules" size="mini">
          <el-row :gutter="20">
            <el-col>
              <el-form-item :label="$t('m.Status')" style="width: 200px;" prop="statusId">
                <el-select  v-model="editForm.statusId" placeholder="">
                  <el-option v-for="rg in status" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="Activity Time" style="width: 200px;" prop="date">
                <el-date-picker v-model="editForm.date" style="width:200px;" type="date" placeholder=""></el-date-picker>
              </el-form-item>
              <el-form-item label="Activity Type" style="width: 200px;" prop="activityTypeId">
                <el-select style="width: 200px" v-model="editForm.activityTypeId" placeholder="">
                  <el-option v-for="i in activityType" :key="i.value" :label="i.text" :value="i.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="Objective" prop="type">
                <div>
                  <el-checkbox-group v-model="editForm.type">
                    <el-checkbox label="1" name="type" style="margin-right: 30px">Introduction</el-checkbox>
                    <el-checkbox label="2" name="type">Make appointment</el-checkbox>
                    <el-checkbox label="3" name="type">Software installation</el-checkbox>
                    <el-checkbox label="4" name="type">Training</el-checkbox>
                    <el-checkbox label="5" name="type">Software troubleshooting</el-checkbox>
                    <el-checkbox label="6" name="type">Complaint</el-checkbox>
                    <el-checkbox label="8" name="type">Data update</el-checkbox>
                    <div class="other" style="width: 300px">
                      <el-checkbox label="7" name="type">Others</el-checkbox>
                      <el-input
                        type="textarea"
                        :rows="4"
                        placeholder=""
                        v-model="editForm.otherObjectives">
                      </el-input>
                    </div>

                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="Result" style="width: 300px;">
                <el-input
                  type="textarea"
                  :rows="4"
                  placeholder=""
                  v-model="editForm.result">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-button type="warning" @click="editSave()" size="medium">Save</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import { getActivityInfo, initRestaurant } from '../../api/mgc_api'
  import { newActivity } from '../../api/zxy_api.js'
  import Qs from 'qs'
  import regions from '@/json/region'
  import townships from '@/json/township'
  import status from '@/json/status'
  // 缅甸语JSON
  import mm_regions from '@/mmJson/region'
  import mm_townships from '@/mmJson/township'
  import mm_status from '@/mmJson/status'
  export default {
    name: 'Activity',
    data() {
      return {
        // 表单字段
        townships: [],
        submitForm: {
          // 表单数据必填字段
          status: null,
          regionId: null,
          townshipId: null,
          name: null,
          street: null,
          phone: null,
        },
        editForm: {
          statusId: null,
          date: null,
          activityTypeId: null,
          type: [],
          result: '',
          otherObjectives: '',
          id: null
        },
        status: [
          { "value": 1, "text": "Active"},
          { "value": 2, "text": "Deleted"}
        ],
        objective: [
          { "value": 1, "text": "Introduction"},
          { "value": 2, "text": "Make appointment"},
          { "value": 3, "text": "Software installation"},
          { "value": 4, "text": "Training"},
          { "value": 5, "text": "Software Troubleshooting"},
          { "value": 6, "text": "Complaint"},
          { "value": 8, "text": "Data update"},
          { "value": 7, "text": "Others"},
        ],
        activityType: [
          { "value": 1, "text": "Call"},
          { "value": 2, "text": "Visit"},
          { "value": 3, "text": "Received call"},
        ],
        id: '',
        tableLoading: false,
        loading1: false,
        tableData: [],
        pageInfo: {
          totalCount: 0,
          totalPages: 0
        },
        dialogFormVisible: false,
        rules: {
          name: [
            {required: true, message: 'please enter name', trigger: 'blur'}
          ],
          phone: [
            {required: true, type: 'number', message: 'please enter phone', trigger: 'change'}
          ],
        },
        editRules: {
          statusId: [
            {required: true, message: 'please select', trigger: 'change'}
          ],
          activityTypeId: [
            {required: true, message: 'Please Select', trigger: 'change'}
          ],
          date: [
            {type: 'date', required: true, message: 'Please Select', trigger: 'change'}
          ],
          type: [
            {type: 'array', required: true, message: 'Please Select', trigger: 'change'}
          ],
        }
      }
    },
    computed: {
      regions() {
        if (this.$store.state.localLang == 'MM') {
          return regions
        } else {
          return regions
        }
      },
      rStatus() {
        if (this.$store.state.localLang == 'MM') {
          return status
        } else {
          return status
        }
      },
    },
    methods: {
      editCancelForm () {
        console.log(1234)
        this.editForm.statusId = null
        this.editForm.activityTypeId = null
        this.editForm.date = null
        this.editForm.type = []
        this.editForm.otherObjectives = ''
        this.editForm.result = ''
        this.editForm.id = null
      },
      getTownships(regionId) {
        let town = []
        this.townships = []
        this.submitForm.townshipId = null

        if (this.$store.state.localLang == 'MM') {
          for (var t of townships) {
            if (regionId === t.regionId) {
              town.push({value: t.value, text: t.text})
            }
          }
        } else {
          for (var t of townships) {
            if (regionId === t.regionId) {
              town.push({value: t.value, text: t.text})
            }
          }
        }
        this.townships = town
      },
      getStatusItem (it) {
        let str = ''
        this.status.forEach((item) => {
          if (item.value == it) {
            str = item.text || ''
          }
        })
        return str
      },
      getActivityTypeItem (it) {
        let str = ''
        this.activityType.forEach((item) => {
          if (item.value == it) {
            str = item.text || ''
          }
        })
        return str
      },
      getObjectiveItem (it) {
        if (it) {
          let itArr = it.split(',')
          let str = ''
          for (var i = 0; i < itArr.length; i++) {
            let itemValue = itArr[i]
            this.objective.forEach((item) => {
              if (item.value == itemValue) {
                str = str + '<p>' + item.text +'</p>'
              }
            })
          }
          return str
        }
      },
      getActivityDate (value) {
        if(!value){
          return ''
        }
        var date = new Date(value)
        var Y = date.getFullYear()
        var m = date.getMonth() + 1
        var d = date.getDate()
        if (m < 10) {
          m = '0' + m
        }
        if (d < 10) {
          d = '0' + d
        }
        var ts = d + '-' + m + '-' + Y
        return ts
      },
      getDate (value) {
        if(!value){
          return ''
        }
        var date = new Date(value)
        var Y = date.getFullYear()
        var m = date.getMonth() + 1
        var d = date.getDate()
        var H = date.getHours()
        var i = date.getMinutes()
        var s = date.getSeconds()
        if (m < 10) {
          m = '0' + m
        }
        if (d < 10) {
          d = '0' + d
        }
        if (H < 10) {
          H = '0' + H
        }
        if (i < 10) {
          i = '0' + i
        }
        if (s < 10) {
          s = '0' + s
        }
        var ts = Y + '-' + m + '-' + d + '  ' + H + ':' + i + ':' + s
        return ts
      },
      // message alert 用于前端错误提示信息
      messageToastErr (msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 1500,
          type: 'error'
        })
      },
      getActivity() {
        this.tableLoading = true
        let params = {
          restaurantId: this.id
        }
        params = Qs.stringify(params)
        getActivityInfo(params)
          .then((res) => {
            let data = res
            console.log(res)
            this.tableData = data.data
            // 分页信息配置
            this.pageInfo.totalPages = data.data.pages
            this.pageInfo.totalCount = data.data.total
            // 清除loading 状态
            setTimeout(() => {
              this.tableLoading = false
            }, 400)
          })
          .catch((error) => {
            // this.showToast(error.errorID)
            // console.log(error)
            this.messageToastErr('error,please refresh the page later')
            setTimeout(() => {
              this.tableLoading = false
            }, 400)
          })
      },
      // 初始化 Dev 表单
      initForm () {
        this.loading1 = true
        initRestaurant(this.id).then((res) => {
          if (res.data) {
            let obj = res.data.info
            this.submitForm.status = obj.status
            this.submitForm.regionId = obj.regionId
            this.getTownships(obj.regionId)
            this.submitForm.townshipId = obj.townshipId
            this.submitForm.name = obj.name
            this.submitForm.street = obj.street
            this.submitForm.phone = Number(obj.phone)
            this.loading1 = false
          }
        }).catch((error) => {
          if (error.response) {
            console.log(error.response)
          } else {
            // 一些错误是在设置请求的时候触发
            console.log('Error', error.message)
          }
          console.log(error.config)
          this.messageToastErr('error,please refresh the page later')
          this.loading1 = false
        })
      },
      editActivity(index, row) {
        this.dialogFormVisible = true
        let objectives = []
        if (row.objectives) {
          objectives = row.objectives.split(",")
        }
        this.editForm.statusId = row.status
        this.editForm.activityTypeId = row.activityType
        this.editForm.date = new Date(row.activityTime)
        this.editForm.type = objectives
        this.editForm.otherObjectives = row.otherObjectives
        this.editForm.result = row.result
        this.editForm.id = row.id
      },
      dateFormat(value) {
        var date = new Date(value)
        var Y = date.getFullYear()
        var m = date.getMonth() + 1
        var d = date.getDate()
        var H = date.getHours()
        var i = date.getMinutes()
        var s = date.getSeconds()
        if (m < 10) {
          m = '0' + m
        }
        if (d < 10) {
          d = '0' + d
        }
        if (H < 10) {
          H = '0' + H
        }
        if (i < 10) {
          i = '0' + i
        }
        if (s < 10) {
          s = '0' + s
        }
        var t = Y + '-' + m + '-' + d
        return t
      },
      editSave() {
        this.tableLoading = true
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            this.dialogFormVisible = false
            let editForm = {
              restaurantId: this.id,
              status: this.editForm.statusId,
              activityTime: this.editForm.date ? this.dateFormat(this.editForm.date) : '',
              activityType: this.editForm.activityTypeId,
              objectives: this.editForm.type ? this.editForm.type.join(',') : '',
              result: this.editForm.result,
              id: this.editForm.id,
            };
            if (this.editForm.type) {
              this.editForm.type.forEach((value, i, arr) => {
                if (value == 7) {
                  editForm.otherObjectives = this.editForm.otherObjectives;
                }
              })
            }
            editForm = Qs.stringify(editForm)
            newActivity(editForm).then((res) => {
                console.log(res)
              if (res) {
                  if (res.data.errorID == 0) {
                    this.getActivity()
                  }
              }

            }).catch((e) => {
              console.log(e)
              this.messageToastErr('error,please refresh the page later')
            })
          } else {
            this.messageToastErr('error submit!!')
            return false;
          }
        });
      },
      addNewActivity() {
        this.$router.push({
          path: '/newActivity',
          query: {
            restaurantId: this.id
          }
        })
      }
    },
    mounted () {
      this.id = this.$route.query.id || ''
      this.initForm()
      this.getActivity()
    }
  }
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .food-content-box .container-padding {
    padding: 20px 40px 0 40px;
  }
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6 !important;
    font-size: 20px !important;
  }

  .breadcrumb {
    margin-bottom: 20px;
  }

  .container-padding {
    padding: 0 40px;
  }

  .activity-info .el-checkbox + .el-checkbox {
    margin-left: 0 !important;
    margin-right: 30px !important;
  }
  .list-notes{
    text-align: center;
    display: block;
  }
</style>
